package com.qindian.coupontest;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.qindian.GoodsAdapter;
import com.qindian.model.CouponModel;
import com.qindian.model.ExchangeModel;
import com.qindian.model.GoodsModel;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Author: Li
 * Date: 2018/5/21 0021
 * Description: 折扣商品列表
 */

public class GoodsListFragment extends BaseFragment implements OnRefreshLoadmoreListener {


    private static final String KEY = "Ypj7fmVAEwyHRcIH6BoBVg3xbGidvnzk";
    private static final String AGENT_ID = "9240";
    private static final String MOBILE = "18852996181";
    private RecyclerView mRecyclerGoods;
    private SmartRefreshLayout mLayoutRefresh;
    private GoodsAdapter mGoodsAdapter;
    private int mPage = 1;
    private boolean mIsRefresh = true;
    private String mType;
    private String mDetail;
    private String mPlatform;
    private String mKeyword;
    private String mCid;
    private int mGap;
    public static GoodsListFragment newInstance(boolean firstVisible, String platform, String type, String detail, String cid, String keyword) {

        Bundle bundle = new Bundle();
        bundle.putBoolean("firstVisible", firstVisible);
        bundle.putString("platform", platform);
        bundle.putString("type", type);
        bundle.putString("detail", detail);
        bundle.putString("cid", cid);
        bundle.putString("keyword", keyword);
        GoodsListFragment fragment = new GoodsListFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_goods_list, container, false);
        mRecyclerGoods = view.findViewById(R.id.recycler_goods);
        mLayoutRefresh = view.findViewById(R.id.layout_refresh);


        if (getArguments() != null) {
            mType = getArguments().getString("type");
            mDetail = getArguments().getString("detail");
            mPlatform = getArguments().getString("platform");
            mKeyword = getArguments().getString("keyword");
            mCid = getArguments().getString("cid");
            if (getArguments().getBoolean("firstVisible")) {
                init();
                getGoodsList(1, mCid);

            }
        }
        return view;
    }

    private void init() {
        mGoodsAdapter = new GoodsAdapter(R.layout.item_goods_coupon, getArguments().getString("type"));
        mRecyclerGoods.setLayoutManager(new GridLayoutManager(getActivity(),2));
        mGap= (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,5,getResources().getDisplayMetrics());
        mRecyclerGoods.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                if (parent.getLayoutManager() instanceof GridLayoutManager) {
                    GridLayoutManager layoutManager= (GridLayoutManager) parent.getLayoutManager();
                    int spanCount=layoutManager.getSpanCount();
                    int pos=parent.getChildAdapterPosition(view);
                        if (pos%spanCount==0) {
                            outRect.left=mGap;
                            outRect.right=mGap/2;
                        } else if (pos % spanCount == spanCount - 1) {
                            outRect.left=mGap/2;
                            outRect.right=mGap;
                        }else {
                            outRect.left=outRect.right=mGap/2;
                        }
                }
                outRect.top=mGap;
            }
        });
        mGoodsAdapter.bindToRecyclerView(mRecyclerGoods);
//        mGoodsAdapter.setEmptyView(R.layout.layout_empty_goods);
//        mGoodsAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
//            @Override
//            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//                GoodsModel.DataBean.ListBean bean = mGoodsAdapter.getData().get(position);
//
//
////                exchangeCoupon(getArguments().getString("type"), bean.getId(), MOBILE);
//
//            }
//        });
        mLayoutRefresh.setOnRefreshLoadmoreListener(this);
        mGoodsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                GoodsModel.DataBean.ListBean bean = mGoodsAdapter.getData().get(position);
                Intent intent = new Intent(mContext, GoodsDetailActivity.class);
                intent.putExtra("pic", bean.getItempic());
                intent.putExtra("gid", bean.getId());
                intent.putExtra("type", mType);
                intent.putExtra("title", bean.getTitle());
                intent.putExtra("originPrice", bean.getOrigin_price());
                String couponPrice="";
                double price= Double.parseDouble(bean.getOrigin_price())-Double.parseDouble(bean.getShop_price());
                switch (mType) {
                    case "tb":
                        couponPrice = String.format(Locale.CHINA, "%.2f", price);
                        break;
                    case "jd":
                        couponPrice=bean.getShop_price();
                        break;
                }
                intent.putExtra("couponPrice", couponPrice);
                intent.putExtra("url",bean.getPlathform_url());
                intent.putExtra("detail",mDetail);
                startActivity(intent);


//                String url = bean.getPlathform_url();
//                switch (mType) {
//                    case "tb":
//                        if (checkPackage("com.taobao.taobao")) {
//                            Intent tbIntent = new Intent();
//                            tbIntent.setAction(Intent.ACTION_VIEW);
//                            tbIntent.setData(Uri.parse(url));
//                            tbIntent.setClassName("com.taobao.taobao", "com.taobao.tao.detail.activity.DetailActivity");
//                            startActivity(tbIntent);
//                        } else {
//                            Intent webIntent = new Intent(getActivity(), WebActivity.class);
//                            webIntent.putExtra("title", "商品详情");
//                            webIntent.putExtra("url", url);
//                            startActivity(webIntent);
//                        }
//                        break;
//                    case "jd":
//                        if (checkPackage("com.jingdong.app.mall")) {
//                            String id = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".html"));
//                            Log.e("tag", "onItemClick: " + id);
//                            String uri = "openapp.jdmobile://virtual?params=" +
//                                    "{\"sourceValue\":\"0_productDetail_97\"," +
//                                    "\"des\":\"productDetail\"," +
//                                    "\"skuId\":\"" + id + "\"," +
//                                    "\"category\":\"jump\"," +
//                                    "\"sourceType\":\"homefloor\"}";
//                            Intent jdIntent = new Intent();
//                            jdIntent.setData(Uri.parse(uri));
//                            startActivity(jdIntent);
//                        } else {
//                            Intent webIntent = new Intent(getActivity(), WebActivity.class);
//                            webIntent.putExtra("title", "商品详情");
//                            webIntent.putExtra("url", url);
//                            startActivity(webIntent);
//                        }
//                        break;
//                }
            }
        });
    }


    @Override
    protected void onFirstVisible() {
        super.onFirstVisible();
        if (getArguments() != null) {
            if (!getArguments().getBoolean("firstVisible")) {
                init();
                getGoodsList(1, mCid);
            }
        }
    }

    /**
     * 获取优惠商品列表
     *
     * @param page 页码
     */
    private void getGoodsList(int page, String cId) {
        if (mGoodsAdapter.getData().size() == 0) {
            showLoadingDialog();
        }
        Map<String, Object> map = new HashMap<>();
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        String prefix = "agent_id=" + AGENT_ID + "&page=" + page;
        if (!TextUtils.isEmpty(cId)) {
            prefix = "agent_id=" + AGENT_ID + "&cid=" + cId + "&page=" + page;
            map.put("cid", cId);
        }

        if (!TextUtils.isEmpty(mKeyword)) {
            prefix = "agent_id=" + AGENT_ID + "&keyword=" + mKeyword + "&page=" + page;
            map.put("keyword", mKeyword);
        }


        String token = MD5Util.getMD5(prefix + time + KEY);

        map.put("agent_id", AGENT_ID);
        map.put("time", time);
        map.put("token", token);
        map.put("page", page);
        RetrofitHelper.createService().getGoodsList(mPlatform, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<GoodsModel>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(GoodsModel goodsModel) {
                        dismissLoadingDialog();
                        if (mIsRefresh) {
                            mPage = 1;
                            mGoodsAdapter.setNewData(goodsModel.getData().getList());
                            if (mGoodsAdapter.getData().size() > 0) {
                                mRecyclerGoods.scrollToPosition(0);
                            }
                            if (goodsModel.getData().getTotal()
                                    > mGoodsAdapter.getData().size()) {
                                mLayoutRefresh.setLoadmoreFinished(false);
                            } else {
                                mLayoutRefresh.setLoadmoreFinished(true);
                            }
                        } else {
                            mGoodsAdapter.addData(goodsModel.getData().getList());
                            if (goodsModel.getData().getTotal()
                                    > mGoodsAdapter.getData().size()) {
                                mPage++;
                                mLayoutRefresh.setLoadmoreFinished(false);
                            } else {
                                mLayoutRefresh.setLoadmoreFinished(true);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                        stopRefreshLoad();
                        if (e instanceof JsonSyntaxException) {
                            mGoodsAdapter.setNewData(new ArrayList<GoodsModel.DataBean.ListBean>());
                        } else {
                            showToast("网络连接错误");

                        }
                        Log.e("tag", "onError: " + e.toString());

                    }

                    @Override
                    public void onComplete() {
                        stopRefreshLoad();
                    }
                });
    }

    private void exchangeCoupon(String type, final String gid, String mobile) {

        showLoadingDialog("正在兑换...");
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        Map<String, Object> map = new HashMap<>();
        map.put("type", type);
        map.put("gid", gid);
        map.put("mobile", mobile);
        map.put("agent_id", AGENT_ID);
        map.put("time", time);

        String prefix = "agent_id=" + AGENT_ID + "&gid=" + gid + "&mobile=" + mobile + "&type=" + type;
        String token = MD5Util.getMD5(prefix + time + KEY);
        map.put("token", token);

        RetrofitHelper.createService().exchangeCoupon(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ExchangeModel>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ExchangeModel exchangeModel) {
//                        switch (exchangeModel.getCode()) {
//                            case "400001":
//                            case "000000":
//                                getCoupon(gid);
////
//                                break;
//                            default:
//                                showToast(exchangeModel.getMsg());
//                                break;
//                        }
                        getCoupon(gid);
                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast(e.toString());
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onComplete() {
                        dismissLoadingDialog();
                    }
                });

    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mIsRefresh = false;
        getGoodsList(mPage + 1, mCid);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        mIsRefresh = true;
        getGoodsList(1, mCid);
    }

    private void stopRefreshLoad() {
        mLayoutRefresh.finishRefresh();
        mLayoutRefresh.finishLoadmore();

    }

    /**
     * 获取优惠券
     *
     * @param id 商品id
     */
    private void getCoupon(String id) {
        showLoadingDialog("正在获取优惠券地址");
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        Map<String, Object> map = new HashMap<>();
        map.put("agent_id", AGENT_ID);
        map.put("time", time);
        map.put("id", id);
        String prefix = "agent_id=" + AGENT_ID + "&id=" + id;
        map.put("token", MD5Util.getMD5(prefix + time + KEY));
        RetrofitHelper.createService().getCoupon(mDetail, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())

                .subscribe(new Observer<CouponModel>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(CouponModel couponModel) {
                        if (couponModel.getCode().equals("000000")) {
                            String json = new Gson().toJson(couponModel, CouponModel.class);
                            try {
                                JSONObject object = new JSONObject(json).getJSONObject("data");
                                String url = object.getString("coupon_url");
                                switch (mDetail) {
                                    case "jddetail":
                                        Intent jdIntent = new Intent(getActivity(), WebActivity.class);
                                        jdIntent.putExtra("url", url);
                                        jdIntent.putExtra("title", "京东优惠券");
                                        startActivity(jdIntent);
                                        break;
                                    case "tbdetail":
                                        if (checkPackage("com.taobao.taobao")) {
                                            Intent tbIntent = new Intent();
                                            tbIntent.setAction(Intent.ACTION_VIEW);
                                            tbIntent.setData(Uri.parse(url));
                                            tbIntent.setClassName("com.taobao.taobao", "com.taobao.browser.BrowserActivity");
                                            startActivity(tbIntent);
                                        } else {
                                            showToast("请先安装手机淘宝APP");
                                        }

                                        break;
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        } else {
                            showToast(couponModel.getMsg());
                        }
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast(e.toString());
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private boolean checkPackage(String packageName) {
        PackageManager manager = getActivity().getPackageManager();
        List<PackageInfo> packages = manager.getInstalledPackages(0);
        for (PackageInfo info : packages) {
            if (info.packageName.equals(packageName)) {
                return true;
            }
        }
        return false;
    }
}
